package com.shouhuobao.samecity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.collectplus.express.BaseActivity2;
import com.collectplus.express.R;
import com.collectplus.express.alipay.PayResult;
import com.collectplus.express.app.Animator;
import com.collectplus.express.app.Intents;
import com.collectplus.express.logic.AppCache;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppLogic;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.DialogMgr;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.menu.WebViewActivity;
import com.collectplus.express.model.CouponBean;
import com.collectplus.express.model.SameCityHistoryBean;
import com.collectplus.express.model.SameCityOrderBackBean;
import com.collectplus.express.model.SameCityPriceBean;
import com.collectplus.express.model.SameCityPriceOrderBean;
import com.collectplus.express.self.SelfOrderPayStampAdapter;
import com.collectplus.express.view.HorizontalListView;
import com.collectplus.express.wxapi.WXPayEntryActivity;
import com.shb.model.OrderPayBean;
import com.shb.model.WxPayModel;
import com.shouhuobao.bhi.stamp.StampStoreActivity;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import droid.frame.app.Callback;
import droid.frame.ui.dialog.AppDialog;
import droid.frame.ui.utils.Utils;
import droid.frame.umeng.UMeng;
import droid.frame.utils.GlideUtil;
import droid.frame.utils.android.MathUtils;

/**
 * 确认支付
 * Created by lidandan on 2017/12/27.
 */
public class SameCityOrderActivity extends BaseActivity2 implements View.OnClickListener {
    private final int SDK_PAY_FLAG = 1;
    private final int SDK_CHECK_FLAG = 2;

    private CheckBox mStampCheckBox;//邮票选择按钮
    private CheckBox mWXCheckBox;//微信选择按钮
    private CheckBox mALiCheckBox;//支付宝选择按钮
    private String orderId;//订单id
    private SameCityOrderBackBean resultBean = null;
    private SameCityPriceBean mPriceBean = null;
    private boolean isRequest = false;//只有在当前activity处于后台时，才设置为true
    private boolean isWxFrom = false;//判断是不是微信支付之后取消的 true是微信支付返回来的  false不是微信支付返回来的
    private String realCost = "0.0";

    private PopupWindow popwin = null;
    private TextView mStampName;// 邮票名称
    private TextView mStampHint;// 邮票剩余提示
    private TextView mCurrentStampNumTV;//当前可用邮票数量
    private CouponBean couponBean = null;//用于保存当前点击的邮票对象
    private String stampOrderId = "";//新加使用邮票支付
    private boolean stampButtonCheck = false;//判断邮票是否选择
    private TextView mRealCostTV;
    private TextView mIsUseStampTV;//已使用邮票
    private TextView mReceiverDown;// 下拉抽屉按钮

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        orderId = getIntent().getStringExtra("orderId");
        super.onCreate(savedInstanceState);
        if (isNotEmpty(orderId)) {
            showLoadingDialog(null);
            AppHttp.getInstance().querySameCityOrderDetail(orderId);
        }
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.same_city_order_activity);
        super.findViewById();
        getAppTitle().setCommonTitle("确认支付");
        findViewById(R.id.order_pay_tv).setOnClickListener(this);
        findViewById(R.id.samecity_moneydetail_iv).setOnClickListener(this);
        mStampName = (TextView) findViewById(R.id.stamp_name);
        mStampHint = (TextView) findViewById(R.id.stamp_hint);
        mCurrentStampNumTV = (TextView) findViewById(R.id.currentstampnumTV);
        mStampCheckBox = (CheckBox) findViewById(R.id.pay_stamp_checkBox);
        mStampCheckBox.setOnClickListener(this);
        mWXCheckBox = (CheckBox) findViewById(R.id.pay_wx_checkBox);
        mWXCheckBox.setOnClickListener(this);
        mALiCheckBox = (CheckBox) findViewById(R.id.pay_ali_checkBox);
        mALiCheckBox.setOnClickListener(this);
        findViewById(R.id.pay_ali_layout).setOnClickListener(this);
        findViewById(R.id.pay_wx_layout).setOnClickListener(this);
        findViewById(R.id.pay_stamp_layout).setOnClickListener(this);
        mRealCostTV = (TextView) findViewById(R.id.pay_price_tv);
        mIsUseStampTV = (TextView) findViewById(R.id.is_user_stamp_tip_tv);
        findViewById(R.id.samecity_drawer_layout).setOnClickListener(this);
        mReceiverDown = (TextView) findViewById(R.id.receiver_down);
        findViewById(getResources().getIdentifier("title_left_switcher", "id", getPackageName())).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alterDialog();
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            //展示费用明细
            case R.id.samecity_moneydetail_iv:
                showChoosePop();
                break;
            //价格规则
            case R.id.price_order_tv:
                intent = new Intent(getContext(), WebViewActivity.class);
                intent.putExtra("title", "计价规则");
                startActivity(intent);
                break;
            //选择支付宝
            case R.id.pay_ali_layout:
            case R.id.pay_ali_checkBox:
                if (resultBean == null) {
                    return;
                }
                //如果没有邮票或者为普通邮票,那么只能进行单选
                if (couponBean == null || (!isNormalStamp(couponBean.getStampType()) && !nomarlStampOverPrice())) {
                    mIsUseStampTV.setVisibility(View.GONE);
                    stampButtonCheck = false;
                    realCost = resultBean.getCost();
                    mALiCheckBox.setChecked(true);
                    mStampCheckBox.setChecked(false);
                    mWXCheckBox.setChecked(false);
                    mRealCostTV.setText("￥" + realCost);
                } else {
                    mALiCheckBox.setChecked(true);
                    mWXCheckBox.setChecked(false);
                }
                break;
            //选择微信支付
            case R.id.pay_wx_layout:
            case R.id.pay_wx_checkBox:
                if (resultBean == null) {
                    return;
                }
                //普通邮票或者没有邮票，只能进行单选
                if (couponBean == null || (!isNormalStamp(couponBean.getStampType()) && !nomarlStampOverPrice())) {
                    mIsUseStampTV.setVisibility(View.GONE);
                    stampButtonCheck = false;
                    realCost = resultBean.getCost();
                    mStampCheckBox.setChecked(false);
                    mALiCheckBox.setChecked(false);
                    mWXCheckBox.setChecked(true);
                    mRealCostTV.setText("￥" + realCost);
                } else {//折扣邮票
                    mALiCheckBox.setChecked(false);
                    mWXCheckBox.setChecked(true);
                }
                break;
            //选中邮票支付或取消邮票支付
            case R.id.pay_stamp_checkBox:
                if (resultBean == null) {
                    return;
                }
                if (resultBean.getStampOrders().size() > 0) {
                    if (couponBean == null) {
                        return;
                    }
                    //如果为普通邮票只能进行单选
                    if (!isNormalStamp(couponBean.getStampType()) && !nomarlStampOverPrice()) {//如果为正常普通邮票
                        //如果按钮为未选中状态
                        if (!stampButtonCheck) {
                            mIsUseStampTV.setVisibility(View.VISIBLE);
                            //需要支付金额
                            stampButtonCheck = true;
                            mStampCheckBox.setChecked(true);
                            mWXCheckBox.setChecked(false);
                            mALiCheckBox.setChecked(false);
                            realCost = "0.0";
                        } else {//取消使用邮票
                            mIsUseStampTV.setVisibility(View.GONE);
                            //不说明需要支付金额
                            stampButtonCheck = false;
                            mStampCheckBox.setChecked(false);
                            if (!mWXCheckBox.isChecked()) {
                                mALiCheckBox.setChecked(true);
                            }
                            realCost = resultBean.getCost();
                        }
                        mRealCostTV.setText("￥" + realCost);
                    } else {//打折邮票
                        if (mStampCheckBox.isChecked()) {//选中邮票
                            mIsUseStampTV.setVisibility(View.VISIBLE);
                            stampButtonCheck = true;
                            mStampCheckBox.setChecked(true);
                            if (!mWXCheckBox.isChecked()) {
                                mALiCheckBox.setChecked(true);
                            }
                            double price = computePrice(couponBean.getStampType());
                            realCost = (price <= 0 ? 0.01 : price) + "";
                        } else {//取消选中邮票
                            mIsUseStampTV.setVisibility(View.GONE);
                            if (!mWXCheckBox.isChecked()) {
                                mALiCheckBox.setChecked(true);
                            }
                            realCost = resultBean.getCost();
                            stampButtonCheck = false;
                            mStampCheckBox.setChecked(false);
                        }
                        mRealCostTV.setText("￥" + realCost);
                    }
                }
                break;
            //立即支付
            case R.id.order_pay_tv:
            case R.id.order_pay_tv1://费用明细中的立即支付
                //支付宝支付
                if (mALiCheckBox.isChecked()) {
                    showLoadingDialog(null);
                    if (couponBean != null && (isNormalStamp(couponBean.getStampType()) || nomarlStampOverPrice()) && mStampCheckBox.isChecked()) {
                        AppHttp.getInstance().sameCityAliPay(orderId, realCost, realCost, Integer.parseInt(stampOrderId));
                    } else {
                        AppHttp.getInstance().sameCityAliPay(orderId, realCost, realCost, 0);
                    }
                } else if (mWXCheckBox.isChecked()) {
                    //微信支付
                    final IWXAPI wxapi = WXAPIFactory.createWXAPI(this, null);
                    if (wxapi.isWXAppInstalled() == false) {
                        showToast("未安装微信");
                        return;
                    }
                    showLoadingDialog(null);
                    WXPayEntryActivity.payFrom = 2;
                    if (couponBean != null && (isNormalStamp(couponBean.getStampType()) || nomarlStampOverPrice()) && mStampCheckBox.isChecked()) {
                        AppHttp.getInstance().sameCityWeiXinPay(orderId, realCost, realCost, Integer.parseInt(stampOrderId));
                    } else {
                        AppHttp.getInstance().sameCityWeiXinPay(orderId, realCost, realCost, 0);
                    }
                } else if (mStampCheckBox.isChecked()) {
                    if (isEmpty(stampOrderId)) {
                        return;
                    }
                    UMeng.click(getContext(), "orderpay_stamp_click");
                    isWxFrom = false;
                    showLoadingDialog(null);
                    AppHttp.getInstance().stampPay(orderId, stampOrderId);
                } else {
                    showToast("请选择支付方式");
                }
                if (popwin != null) {
                    popwin.dismiss();
                }
                break;
            // 邮票支付
            case R.id.pay_stamp_layout:
                if (resultBean.getStampOrders().size() > 0) {
                    popupWindowView();
                } else {
                    intent = new Intent(this, StampStoreActivity.class);
                    intent.putExtra("from", 1);
                    startActivityForResult(intent, 101);
                }
                break;
            // 最下面抽屉
            case R.id.samecity_drawer_layout:
                ViewGroup drawerLayout = (ViewGroup) findViewById(R.id.goods_info_ll);
                int height = Utils.dpToPx(160, getResources());
                // 如果是寄件人
                if (drawerLayout.getVisibility() == View.VISIBLE) {
                    mReceiverDown.setText("查看更多");
                    Drawable drawableRight = getResources().getDrawable(R.drawable.drawer_down);
                    mReceiverDown.setCompoundDrawablesWithIntrinsicBounds(null, null, drawableRight, null);
                    mReceiverDown.setCompoundDrawablePadding(Utils.dpToPx(5, getResources()));
                    //                    mReceiverDown.setImageDrawable(getResources().getDrawable(R.drawable.drawer_down));
                    Animator.scaleY(drawerLayout, null, height, 0);
                } else {
                    drawerLayout.setVisibility(View.VISIBLE);
                    mReceiverDown.setText("点击收起");
                    Drawable drawableRight = getResources().getDrawable(R.drawable.drawer_up);
                    mReceiverDown.setCompoundDrawablesWithIntrinsicBounds(null, null, drawableRight, null);
                    mReceiverDown.setCompoundDrawablePadding(Utils.dpToPx(5, getResources()));
                    //                    mReceiverDown.setImageDrawable(getResources().getDrawable(R.drawable.drawer_up));
                    Animator.scaleY(drawerLayout, new Callback() {
                        @Override
                        public void execute(Object... result) {
                        }
                    }, 0, height);
                }
                break;
        }
    }

    /**
     * 展示底部弹出的dialog
     */
    private void showChoosePop() {
        final View layout = LayoutInflater.from(this).inflate(R.layout.samecity_order_money_detail_pop, null);
        //
        popwin = DialogMgr.createPopupWindow(this, layout);
        popwin.showAtLocation(this.findViewById(R.id.order_pay_tv), Gravity.RIGHT | Gravity.BOTTOM, 0, 0);
        //关闭
        layout.findViewById(R.id.samecity_moneydetail_iv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popwin.dismiss();
            }
        });
        //基础配送费
        TextView basePriceTV = (TextView) layout.findViewById(R.id.base_price_tv);
        //距离
        TextView distanceTV = (TextView) layout.findViewById(R.id.distance_tv);
        //距离价格
        TextView distancePriceTV = (TextView) layout.findViewById(R.id.distance_price_tv);
        //重量
        TextView weightTV = (TextView) layout.findViewById(R.id.weight_tv);
        //重量价格
        TextView weightPriceTV = (TextView) layout.findViewById(R.id.weight_price_tv);
        //支付的价格
        TextView payMoneyTV = (TextView) layout.findViewById(R.id.pay_money_tv);
        //距离和重量展示
        TextView distanceWeightTV = (TextView) layout.findViewById(R.id.distance_weight_tv);
        layout.findViewById(R.id.price_order_tv).setOnClickListener(this);
        layout.findViewById(R.id.order_pay_tv1).setOnClickListener(this);
        //使用了邮票
        if (stampButtonCheck) {
            layout.findViewById(R.id.is_user_stamp_tip_tv).setVisibility(View.VISIBLE);
            layout.findViewById(R.id.stamp_layout_ll).setVisibility(View.VISIBLE);
            if (couponBean != null) {
                //普通邮票
                if (!isNormalStamp(couponBean.getStampType()) && !nomarlStampOverPrice()) {
                    ((TextView) layout.findViewById(R.id.stamp_price_tv)).setText("-￥" + resultBean.getCost());
                } else {
                    ((TextView) layout.findViewById(R.id.stamp_price_tv)).setText("-￥" + MathUtils.round(MathUtils.sub(resultBean.getCost(), realCost), 2));
                }
            } else {
                layout.findViewById(R.id.stamp_layout_ll).setVisibility(View.GONE);
            }
        } else {
            layout.findViewById(R.id.is_user_stamp_tip_tv).setVisibility(View.GONE);
            layout.findViewById(R.id.stamp_layout_ll).setVisibility(View.GONE);
        }
        payMoneyTV.setText("￥" + realCost);
        if (resultBean != null && resultBean.getPriceMap() != null) {
            SameCityPriceOrderBean bean = resultBean.getPriceMap();
            basePriceTV.setText("￥" + bean.getStartPrice());
            distanceTV.setText(bean.getDistance() + "公里");
            distancePriceTV.setText("￥" + bean.getDistancePrice());
            weightTV.setText(bean.getWeight() + "kg");
            weightPriceTV.setText("￥" + bean.getWeightPrice());
            distanceWeightTV.setText("(" + bean.getDistanceTotal() + "公里," + bean.getWeightTotal() + "kg)");
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            //订单详情返回
            case MsgID.query_samecity_order_detail:
                cancelLoadingDialog();
                final AppResult<SameCityOrderBackBean> result = JSON.parser(msg.obj, SameCityOrderBackBean.class);
                if (result.isSuccess()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            resultBean = result.getResult();
                            mPriceBean = resultBean.getCgp();
                            updateView();
                        }
                    });
                } else {
                    showToast(result.getMessage());
                }
                return true;
            //邮票支付
            case MsgID.stamp_pay:
                cancelLoadingDialog();
                AppResult<?> stampResult = JSON.parser(msg.obj.toString());
                if (stampResult != null && stampResult.isSuccess()) {
                    showToast("支付成功");
                    AppLogic.getInstance().onPaySuccess(getContext());
                    SameCityOrderActivity.super.finish();
                }
                return false;
            //微信支付回传
            case MsgID.samecity_weiXinPay:
                cancelLoadingDialog();
                final AppResult<WxPayModel> wxResult = JSON.parser(msg.obj.toString(), WxPayModel.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (wxResult == null) {
                            showToast("服务器异常");
                            return;
                        }
                        if (wxResult.isSuccess()) {
                            WxPayModel wxModel = wxResult.getResult();
                            if (wxModel == null) {
                                showToast("服务器异常");
                                return;
                            }
                            com.shb.model.OrderPayBean pay = new com.shb.model.OrderPayBean(wxModel);
                            handleWxpay(pay);
                            isWxFrom = true;
                            isRequest = false;
                        } else {
                            showToast(wxResult.getMessage());
                        }
                    }
                });
                return true;
            //支付宝支付
            case MsgID.samecity_aliPay:
                cancelLoadingDialog();
                final AppResult<?> aliResult = JSON.parser(msg.obj.toString());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (aliResult.getResult() == null) {
                            showToast("服务器异常");
                            return;
                        }
                        if (aliResult.isSuccess()) {
                            alipay(aliResult.getResult().toString());
                            isRequest = false;
                            isWxFrom = false;
                        } else {
                            showToast(aliResult.getMessage());
                        }
                    }
                });
                return true;
            default:
                return super.handleMessage(msg);
        }

    }

    /**
     * 更新布局
     */
    private void updateView() {
        if (resultBean != null) {
            realCost = resultBean.getCost();
            if (isNotEmpty(resultBean.getOrderId())) {
                AppCache.setOrderId(Integer.parseInt(resultBean.getOrderId()));
            }
            if (isNotEmpty(resultBean.getParcelId())) {
                AppCache.setParcelId(Integer.parseInt(resultBean.getParcelId()));
            }
            SameCityHistoryBean senderBean = resultBean.getVisit();
            SameCityHistoryBean receiveBean = resultBean.getTargetVisit();
            SameCityPriceOrderBean priceOrderBean = resultBean.getPriceMap();
            if (senderBean != null) {
                //寄件人地址  建筑物的名称+详细地址
                ((TextView) findViewById(R.id.sender_address_tv)).setText(senderBean.getBuildName() + "   （" + senderBean.getAddress() + senderBean.getAddressDesc() + "）");
                //寄件人信息 姓名+手机号
                ((TextView) findViewById(R.id.sender_info_tv)).setText(senderBean.getName() + "   " + senderBean.getPhone());
            }
            if (receiveBean != null) {
                //收件人地址  建筑物的名称+详细地址
                ((TextView) findViewById(R.id.receive_address_tv)).setText(receiveBean.getBuildName() + "   （" + receiveBean.getAddress() + receiveBean.getAddressDesc() + "）");
                //收件人信息 姓名+手机号
                ((TextView) findViewById(R.id.receive_info_tv)).setText(receiveBean.getName() + "   " + receiveBean.getPhone());
            }
            //包裹图片
            GlideUtil.loadImage(getContext(), resultBean.getParcelImgUrl(), R.drawable.parcel_goods_default, (ImageView) findViewById(R.id.goods_iv));
            //包裹名称
            ((TextView) findViewById(R.id.goods_name_tv)).setText("物品信息：" + resultBean.getCategory());
            //包裹重量
            if (resultBean.getWeight() >= 5) {
                ((TextView) findViewById(R.id.goods_weight_tv)).setText(resultBean.getWeight() + "kg");
            } else {
                ((TextView) findViewById(R.id.goods_weight_tv)).setText("5kg以下");
            }
            if (priceOrderBean != null) {
                realCost = priceOrderBean.getTotalPrice() + "";
                //需要支付的价格
                mRealCostTV.setText("￥" + priceOrderBean.getTotalPrice());
                //距离，重量
                ((TextView) findViewById(R.id.distance_weight_tv)).setText("(" + priceOrderBean.getDistanceTotal() + "公里," + priceOrderBean.getWeightTotalDesc() + ")");
            }
            //邮票相关设置
            //如果有邮票
            if (resultBean.getStampOrders().size() > 0) {
                mCurrentStampNumTV.setVisibility(View.VISIBLE);
                mStampCheckBox.setVisibility(View.VISIBLE);
                mStampHint.setVisibility(View.GONE);
                if (couponBean == null) {
                    couponBean = resultBean.getStampOrders().get(0);
                }
                mStampName.setText(couponBean.getStampName());
                stampOrderId = couponBean.getStampOrderId();
                int couponNum = 0;
                for (CouponBean couponBean : resultBean.getStampOrders()) {
                    couponNum += Integer.valueOf(couponBean.getStampNum());
                }
                mCurrentStampNumTV.setText("点击可选,共" + couponNum + "张");
                //判断是否为折扣邮票，如果是折扣邮票，默认选中支付宝支付
                //折扣邮票或者抵扣邮票,或者超出邮票的使用范围
                if (isNormalStamp(couponBean.getStampType()) || nomarlStampOverPrice()) {
                    mIsUseStampTV.setVisibility(View.VISIBLE);
                    if (!mWXCheckBox.isChecked()) {
                        mALiCheckBox.setChecked(true);
                    }
                    stampButtonCheck = true;
                    mStampCheckBox.setChecked(true);
                    mIsUseStampTV.setVisibility(View.VISIBLE);
                    double price = computePrice(couponBean.getStampType());
                    realCost = (price <= 0 ? 0.01 : price) + "";
                } else {//普通邮票
                    if (mALiCheckBox.isChecked()) {
                        stampButtonCheck = false;
                        mStampCheckBox.setChecked(true);
                        mALiCheckBox.setChecked(false);
                        mWXCheckBox.setChecked(false);
                    } else if (mWXCheckBox.isChecked()) {
                        stampButtonCheck = false;
                        mStampCheckBox.setChecked(true);
                        mALiCheckBox.setChecked(false);
                        mWXCheckBox.setChecked(false);
                    } else {
                        stampButtonCheck = true;
                        mStampCheckBox.setChecked(true);
                        mALiCheckBox.setChecked(false);
                        mWXCheckBox.setChecked(false);
                        mIsUseStampTV.setVisibility(View.VISIBLE);
                    }
                    realCost = "0.00";
                }
                mRealCostTV.setText("￥" + realCost);
            } else {
                mIsUseStampTV.setVisibility(View.GONE);
                if (mWXCheckBox.isChecked()) {
                    stampButtonCheck = false;
                    mStampCheckBox.setChecked(false);
                    mALiCheckBox.setChecked(false);
                    mWXCheckBox.setChecked(true);
                } else {
                    stampButtonCheck = false;
                    mStampCheckBox.setChecked(false);
                    mALiCheckBox.setChecked(true);
                    mWXCheckBox.setChecked(false);
                }
                mCurrentStampNumTV.setVisibility(View.GONE);
                mRealCostTV.setText("￥" + realCost);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isRequest && isWxFrom == false) {
            if (isNotEmpty(orderId)) {
                showLoadingDialog(null);
                AppHttp.getInstance().querySameCityOrderDetail(orderId);
            }
        }
        isRequest = false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        isRequest = true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {// 竖屏
            alterDialog();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 处理跳转到微信支付
     *
     * @param pay
     */
    private void handleWxpay(OrderPayBean pay) {
        if (pay == null) {
            Toast.makeText(this, "订单数据异常", Toast.LENGTH_SHORT).show();
        } else {
            sendPayReq(pay);
        }
    }

    private void sendPayReq(OrderPayBean pay) {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(pay.getAppid());
        //
        PayReq req = new PayReq();
        if (getIntent() != null) {
            String isCollect = getIntent().getStringExtra("isCollect");
            if (isCollect != null) {
                req.extData = isCollect;
            }
        }
        req.appId = pay.getAppid();
        req.partnerId = pay.getPartnerid();
        req.prepayId = pay.getPrepayid();
        req.packageValue = pay.getPackageValue();
        req.nonceStr = pay.getNoncestr();
        req.timeStamp = pay.getTimestamp();
        req.sign = pay.getSign();
        //
        msgApi.sendReq(req);
    }

    private Handler mPayHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    // String resultInfo = payResult.getResult();
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(getContext(), "支付成功", Toast.LENGTH_SHORT).show();
                        // startActivity(new Intent(OrderPayActivity.this, OrderEvaluateActivity.class));
                        AppHttp.getInstance().orderPayCallBack(resultBean.getOrderId(), 2, 0);
                        AppLogic.getInstance().onPaySuccess(getContext());
                        SameCityOrderActivity.super.finish();
                        resultBean = null;
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(getContext(), "支付结果确认中", Toast.LENGTH_SHORT).show();
                        }
                        // 6001代表支付取消
                        if (TextUtils.equals(resultStatus, "6001")) {

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(getContext(), "支付失败，请重试！", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(getContext(), "检查结果为：" + msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    /**
     * call alipay sdk pay. 调用SDK支付
     */
    public void alipay(final String payInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(SameCityOrderActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mPayHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void alterDialog() {
        final AppDialog dialog = new AppDialog(this);
        dialog.setTitle("提示");
        dialog.setContent("下单5分钟内未支付，订单将被取消哦，请尽快完成支付。");
        dialog.setConfirmClickListener("继续支付", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setCancelClickListener("确认离开", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                SameCityOrderActivity.super.finish();
                // 如果是从下单界面进来的，则结束该界面的时候直接跳转到主页面
                AppCache.setOrderId(0);// 清空订单内容
                Intents.startMainActivityClearTop(getContext());
            }
        });
        dialog.show();
    }

    /**
     * 选择可用邮票
     * 更新popupwindow状态和显示
     */
    @SuppressLint("WrongConstant")
    private void popupWindowView() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.self_orderpay_choose_stamp, null);
        final PopupWindow popupWindow = DialogMgr.createPopupWindow(getContext(), view);
        popupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popupWindow.showAtLocation(findViewById(R.id.order_pay_tv), Gravity.RIGHT | Gravity.BOTTOM, 0, 0);
        HorizontalListView horizontalListView = (HorizontalListView) view.findViewById(R.id.horizontal_lv);
        final SelfOrderPayStampAdapter adapter = new SelfOrderPayStampAdapter(resultBean.getStampOrders(), getContext(), horizontalListView);
        horizontalListView.setAdapter(adapter);
        //关闭按钮
        ImageView closeIV = (ImageView) view.findViewById(R.id.title_right);
        closeIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        horizontalListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CouponBean bean = adapter.getItem(position);
                if (bean == null) {
                    return;
                }
                couponBean = bean;
                //折扣邮票
                if (isNormalStamp(couponBean.getStampType())) {
                    stampButtonCheck = true;
                    mStampCheckBox.setChecked(true);
                    if (!mWXCheckBox.isChecked()) {
                        mALiCheckBox.setChecked(true);
                    }
                    double price = computePrice(couponBean.getStampType());
                    realCost = (price <= 0 ? 0.00 : price) + "";
                    mRealCostTV.setText("￥" + realCost);
                } else {//普通邮票
                    stampButtonCheck = true;
                    mStampCheckBox.setChecked(true);
                    //完全抵消的邮票
                    if (!nomarlStampOverPrice()) {
                        realCost = "0.00";
                        mWXCheckBox.setChecked(false);
                        mALiCheckBox.setChecked(false);
                    } else {
                        //超重或超出距离的选项
                        if (!mWXCheckBox.isChecked()) {
                            mALiCheckBox.setChecked(true);
                        }
                        double price = computePrice(couponBean.getStampType());
                        realCost = (price <= 0 ? 0.00 : price) + "";
                    }
                    mRealCostTV.setText("￥" + realCost);
                }
                stampOrderId = couponBean.getStampOrderId();
                mStampName.setText(couponBean.getStampName());
                popupWindow.dismiss();
            }
        });
    }

    /**
     * 判断是否为普通邮票  true 不是普通邮票  false 为折扣或优惠邮票
     *
     * @param stampType >=11&&<20 属于折扣  >=21属于优惠券
     * @return true 折扣邮票  false 普通邮票
     */
    private boolean isNormalStamp(int stampType) {
        if (stampType >= 11) {
            return true;
        }
        return false;
    }

    /**
     * 计算价钱，折扣邮票用相乘，优惠卷相减
     *
     * @param stampType
     * @return
     */
    private double computePrice(int stampType) {
        //超出邮票使用范围，需要补充价格
        if (nomarlStampOverPrice()) {
            if (resultBean == null || mPriceBean == null) {
                return 0.00;
            }
            double totalDistance = Math.ceil(resultBean.getDistance());
            double totalWeight = resultBean.getWeight();
            double continueDistance = mPriceBean.getContinueDistance();//超出每公里的价格
            double continueWeight = mPriceBean.getContinueWeight();//超出每公斤的价格
            double startDistance = mPriceBean.getStartDistance();//起始距离
            double startPrice = mPriceBean.getStartPrice();//起始价格
            double startWeight = mPriceBean.getStartWeight();//起始重量
            //起始价格+超出重量的价格+超出距离的价格
            double overWeightPrice = 0.00;
            double overDistancePrice = 0.00;
            if (totalWeight > startWeight) {
                overWeightPrice = MathUtils.round(MathUtils.mul(Math.ceil(MathUtils.sub(totalWeight, startWeight)), continueWeight), 2);
            }
            if (totalDistance > startDistance) {
                overDistancePrice = MathUtils.round(MathUtils.mul(Math.ceil(MathUtils.sub(totalDistance, startDistance)), continueDistance), 2);
            }
            //折扣邮票计算   初始价格*邮票的折扣
            if (stampType >= 11 && stampType < 20) {
                if (mStampCheckBox.isChecked()) {
                    return MathUtils.round(MathUtils.add(MathUtils.mul(startPrice, couponBean.getStampValue()), MathUtils.add(overWeightPrice, overDistancePrice)), 2);
                } else {
                    return MathUtils.round(MathUtils.add(MathUtils.add(startPrice, overWeightPrice), overDistancePrice), 2);
                }
            } else if (stampType >= 21 && stampType < 30) {
                double totalPrice = MathUtils.add(startPrice, MathUtils.add(overWeightPrice, overDistancePrice));
                if (mStampCheckBox.isChecked()) {
                    return MathUtils.round(MathUtils.sub(totalPrice, couponBean.getStampValue()), 2);
                } else {
                    return MathUtils.round(MathUtils.add(MathUtils.add(startPrice, overWeightPrice), overDistancePrice), 2);
                }
            } else {
                if (mStampCheckBox.isChecked()) {
                    return MathUtils.round(MathUtils.add(overWeightPrice, overDistancePrice), 2);
                } else {
                    return MathUtils.round(MathUtils.add(MathUtils.add(startPrice, overWeightPrice), overDistancePrice), 2);
                }
            }
        } else {
            if (stampType >= 11 && stampType < 20) {
                return MathUtils.round(MathUtils.mul(Double.parseDouble(resultBean.getCost()), couponBean.getStampValue()), 2);
            } else if (stampType >= 21 && stampType < 30) {
                return MathUtils.round(MathUtils.sub(Double.parseDouble(resultBean.getCost()), couponBean.getStampValue()), 2);
            }
        }
        return 0.00;
    }

    /**
     * 普通邮票 超出规定的重量和距离，按照优惠卷邮票计算
     */
    private boolean nomarlStampOverPrice() {
        if (resultBean == null || mPriceBean == null) {
            return false;
        } else {
            double totalDistance = Math.ceil(resultBean.getDistance());
            double totalWeight = resultBean.getWeight();
            double startDistance = mPriceBean.getStartDistance();//起始距离
            double startWeight = mPriceBean.getStartWeight();//起始重量
            if (totalDistance > startDistance || totalWeight > startWeight) {
                return true;
            } else {
                return false;
            }
        }
    }
}
